// ----------------
// Project:
// ESA Elevator
// ----------------
//
// Description:
// ----------------
// sqrt.v testbench
//
// Version History:
// ----------------
// 140203: added initialisation of CLK
// 140131: added task to kill simulation if necessary
// 140131: added comment simulation finish
// 140131: waiting delays relative to localparam CLK_PERIOD
// 140131: added seperators as comments
// 140131: renamed parameter PERIOD and made it local
// 140116:

`timescale 1ns / 1ps

module sqrt_tb_public;

  //********************* MODULE VALUES ***********************//
	localparam CLK_PERIOD  = 50; // [ns] -> 20 MHz

	// Inputs
	reg CLK;
	reg RESET;
	reg NEXT;
	reg PREVIOUS;

	// Outputs
	wire DONE;
	wire [31:0] SQRT;
  //***********************************************************//  

  //****************** SIMULATION VALUES **********************// 
	
	integer n; //Number count
	integer i; //Iterator for tests
  //***********************************************************//  

  //******************* UUT INSTANTIATION *********************// 
	sqrt uut (
		.CLK(CLK), 
		.RESET(RESET), 
		.NEXT(NEXT), 
		.PREVIOUS(PREVIOUS), 
		.DONE(DONE), 
		.SQRT(SQRT)
	);
  //***********************************************************//

  //******************* 20 MHz CLOCK SIGNAL *******************//   
  always begin 
    #(CLK_PERIOD/2) CLK = ~CLK;
  end
  //***********************************************************// 

  //********************* TEST INITIATION *********************// 
	initial begin
		$display("************ STARTING SIMULATION ************");  
		// Initialize Inputs
		CLK = 0;
		RESET = 1;
		NEXT = 0;
		PREVIOUS = 0;
		n = 1;

		// Wait 100 ns for global reset to finish
		#(2*CLK_PERIOD);
      		RESET = 0;  
		// Add stimulus here
		for(i = 0;i<15;i=i+1) begin
			request_NEXT;
			waitfordone;		
		end
		for(i = 0;i<15;i=i+1) begin
		request_PREVIOUS;
			waitfordone;		
		end

    		$display("************ SIMULATION COMPLETE ************");
		$finish();
	end

initial begin
  #(100000*CLK_PERIOD)
  $display("************ SIMULATION KILLED BECAUSE OF ERROR ************");
  $finish;
end

  //***********************************************************//  
    
  //********************* SIMULATION TASKS ********************//
  task request_NEXT;
     begin
	n = n + 1;
        NEXT = 1;         
         #(1*CLK_PERIOD);
	NEXT = 0;
    end
  endtask  
  
  task request_PREVIOUS;
     begin
	 n = n - 1;
         PREVIOUS  = 1;       
         #(1*CLK_PERIOD);
         PREVIOUS  = 0;
         #(1*CLK_PERIOD);
    end
  endtask 	
	
  task waitfordone;
     begin
	while(DONE == 0) begin
	   #(1*CLK_PERIOD);
	end

	   //Converts 16.16 SQRT into double precision for display
	   $display("Output SQRT of %d is: %f",n,SQRT[31:16]+$bitstoreal({1'b0,11'b01111111111,{SQRT[15:0],36'h000000000}})-1);
     end
  endtask
  //***********************************************************//

endmodule
